package com.ruoyi.web.controller.tool;

import com.ruoyi.kiku.service.utils.DownloadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/api/download")
public class DownloadController {

    @Autowired
    private DownloadService downloadService;

    @PostMapping
    public ResponseEntity<byte[]> downloadFile(
            @RequestParam String fileUrl,
            @RequestParam(required = false) String fileName,
            @RequestParam(defaultValue = "16") int threadCount,
            HttpServletResponse response) throws IOException {

        try {
            System.out.println(fileName);
            byte[] fileBytes = downloadService.downloadFileToMemory(fileUrl, threadCount);
            String contentType = downloadService.detectContentType(fileUrl);
            String finalFileName = downloadService.determineFileName(fileUrl, fileName);
            System.out.println("文件名: " + finalFileName);

            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(finalFileName, "UTF-8")
                    .replaceAll("\\+", "%20"); // 替换+为%20

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(contentType));
            headers.setContentDispositionFormData("attachment", encodedFileName);
            headers.setContentLength(fileBytes.length);
            headers.set("X-File-Integrity", "SHA-256:" + downloadService.calculateFileHash(fileBytes));

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileBytes);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "下载失败: " + e.getMessage() + " | URL: " + fileUrl);
            return null;
        }
    }
}
